package com.example.werewolf.service.impl;

import com.example.werewolf.common.ActionType;
import com.example.werewolf.common.GameStatus;
import com.example.werewolf.entity.Event;
import com.example.werewolf.entity.GameEngine;
import com.example.werewolf.entity.GamePhase;
import com.example.werewolf.entity.Player;
import com.example.werewolf.service.ActionStrategy;
import com.example.werewolf.service.PlayerService;
import com.example.werewolf.utils.PrintUtils;
import com.example.werewolf.utils.RoleUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.example.werewolf.common.WereWolfPrompt.*;

@Service
@RequiredArgsConstructor
public class PlayerServiceImpl implements PlayerService {
    private final ChatClient chatClient;
    private final ActionStrategyFactory strategyFactory;
    private final Map<String, GameEngine> engineMap = new ConcurrentHashMap<>();

    @Override
    public void initGame(String rulesId) {

        // 查询数据库获取玩法基础规则
        System.out.println("当前游戏规则" + "WERE_WOLF_DEFAULT_SYSTEM_RULES");

        // 创建角色并设置身份
        List<Player> defaultPlayers = Player.getDefaultPlayers(chatClient, WERE_WOLF_DEFAULT_SYSTEM_RULES);

        // 获取游戏阶段
        List<GamePhase> gamePhase = GamePhase.getGamePhase();


        // 游戏开始
        GameEngine gameEngine = GameEngine.builder()
                .players(defaultPlayers)
                .phases(gamePhase)
                .systemRules(WERE_WOLF_DEFAULT_SYSTEM_RULES)
                .currentPhaseIndex(0)
                .build();
        engineMap.put("roomId", gameEngine);
//        startGame(gameEngine);
    }

    @Override
    public GameStatus getGameStatus() {
        GameEngine gameEngine = engineMap.get("roomId");
        if (gameEngine == null) {
            return GameStatus.NOT_INITIALIZED;
        } else {
            return GameStatus.IN_PROGRESS;
        }
    }

    @Override
    public void nextStep(String roomId, SseEmitter emitter) throws IOException {
        // 获取游戏对局
        GameEngine gameEngine = engineMap.get(roomId);
        if (gameEngine == null) {
            throw new RuntimeException("游戏对局未找到");
        }

        // 获取当前游戏信息：阶段，公共信息，参与玩家， 阶段 如：第一天白天，第一天夜晚
        GamePhase phase = gameEngine.getPhases().get(gameEngine.getCurrentPhaseIndex());
        List<Event> publicEvents = new ArrayList<>();
        if (gameEngine.getPublicEvents() != null) {
            publicEvents = gameEngine.getPublicEvents();
        }
        List<Player> allPlayers = gameEngine.getPlayers();
        if (phase == null) {
            throw new RuntimeException("游戏阶段异常");
        }

        PrintUtils.printSystem(emitter, phase.getPhaseName());

        // 根据当前游戏阶段，唤醒对应的角色
        List<String> possibleActions = phase.getPossibleActions();
        for (String possibleAction : possibleActions) {
            // 行动类型，唤醒不同的角色
            ActionType actionType = ActionType.fromDescription(possibleAction);
            String playerType = actionType.getPlayerType();
            ActionStrategy strategy = strategyFactory.getStrategy(actionType);
            if (strategy == null) {
                throw new RuntimeException("游戏结束");
            }
            // 选择本次行动的角色
            List<Player> actionPlayers = RoleUtils.findActionPlayers(allPlayers, playerType);
            // 角色行动以及行动后记录
            strategy.execute(allPlayers, actionPlayers, phase, publicEvents, emitter);

            // 行动后处理（狼人刀人反馈，女巫救人毒人反馈，侦探验人反馈，放逐投票后反馈）
//            actionSkill(allPlayers, actionSkill, emitter);
        }
//        showAllPlayersStatus(allPlayers, publicEvents);
        gameEngine.incrementCurrentPhaseIndex();
        gameEngine.setPublicEvents(publicEvents);
        engineMap.put("roomId", gameEngine);
    }
}
